import { APP_ID } from '../core/const';
import { logger } from '../core/logger';
import common from '@ohos.app.ability.common';
import distributedKVStore from '@ohos.data.distributedKVStore';

export class storageService {
  private static _instance: storageService;

  static get instance(): storageService {
    return this._instance;
  }

  static createInstance(context: common.Context): storageService {
    if (this._instance == null)
      this._instance = new storageService(context);
    return this._instance;
  }

  private kvStore: distributedKVStore.SingleKVStore;
  private readonly kvManager: distributedKVStore.KVManager;

  private constructor(context: common.Context) {
    try {
      this.kvManager = distributedKVStore.createKVManager({
        context: context,
        bundleName: APP_ID
      });
    } catch (err) {
      logger.instance.error(err);
    }
  }

  async init() {
    this.kvStore = await this.kvManager.getKVStore<distributedKVStore.SingleKVStore>('storageService', {
      createIfMissing: true,
      encrypt: false,
      backup: false,
      autoSync: false,
      kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
      securityLevel: distributedKVStore.SecurityLevel.S1
    });
  }

  async put(key: string, value: string) {
    await this.kvStore.put(key, value);
  }

  async get(key: string) {
    const value = await this.kvStore.get(key);
    return value?.toString();
  }

  async getParse<T>(key: string) {
    const value = await this.kvStore.get(key);
    const str = value?.toString();
    if (str) {
      const obj: T = JSON.parse(str);
      return obj;
    }
    return undefined;
  }

  async delete(key: string) {
    await this.kvStore.delete(key);
  }

  async close() {
    await this.kvManager.closeKVStore(APP_ID, 'storageService');
  }
}